package com.webserver.controller;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.core.DispatcherServlet;
import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Controller
public class UserController {
    public static File userDir;
    public static File root;
    public static File staticDir;
    static {//静态块不能抛异常
        try {
            root=new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir=new File(root,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        userDir=new File("./user");
        if (!userDir.exists()){
            userDir.mkdirs();
        }
    }
    @RequestMapping("/myweb/reg")
    public void reg(HttpServletRequest request, HttpServletResponse response){
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String nickname=request.getParameter("nickname");
        String ageStr=request.getParameter("age");
        String regex="\\d+";
        if (username==null||password==null||nickname==null||ageStr==null||!ageStr.matches(regex)){
            /*File file=new File(staticDir,"/myweb/reg_input_error.html");
            response.setContentFile(file);*/
            response.sendRedirect("/myweb/reg_input_error.html");
            return;
        }
        int age=Integer.parseInt(ageStr);
        //将用户信息保存到硬盘上
        File userFile=new File(userDir,username+".obj");
        if (userFile.exists()){
            /*File file=new File(staticDir,"/myweb/have_user.html");
            response.setContentFile(file);*/
            response.sendRedirect("/myweb/have_user.html");
            return;
        }
        try {
            FileOutputStream fos=new FileOutputStream(userFile);
            ObjectOutputStream oos=new ObjectOutputStream(fos);
            User user=new User(username,password,nickname,age);
            oos.writeObject(user);
            /*File file=new File(staticDir,"/myweb/reg_success.html");
            response.setContentFile(file);*/
            response.sendRedirect("/myweb/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/myweb/login")
    public void login(HttpServletRequest request,HttpServletResponse response){
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        if (username==null||password==null){
            /*File file=new File(staticDir,"/myweb/login_info_error.html");
            response.setContentFile(file);*/
            response.sendRedirect("/myweb/login_info_error.html");
            return;
        }
        File userFile=new File(userDir,username+".obj");
        if (userFile.exists()){
            User user= null;
            try(FileInputStream fis=new FileInputStream(userFile);
                ObjectInputStream ois=new ObjectInputStream(fis);) {

                user = (User)ois.readObject();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (user.getPassword().equals(password)){
                /*File file=new File(staticDir,"/myweb/login_success.html");
                response.setContentFile(file);*/
                response.sendRedirect("/myweb/login_success.html");
                return;
            }
        }
        /*File file=new File(staticDir,"/myweb/login_fail.html");
        response.setContentFile(file);*/
        response.sendRedirect("/myweb/login_fail.html");
    }
    @RequestMapping("/myweb/showAllUser")
    public void showAllUser(HttpServletRequest request,HttpServletResponse response){
        List<User> userList=new ArrayList<>();
        File[] files=userDir.listFiles(f->f.getName().endsWith(".obj"));
        System.out.println(Arrays.toString(files));
        for (File file:files){
            try(FileInputStream fis=new FileInputStream(file);
                ObjectInputStream ois=new ObjectInputStream(fis);) {

                User user=(User)ois.readObject();
                userList.add(user);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println(userList);
        PrintWriter pw=response.getWriter();
        response.setContentType("text/html");

        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">");
        pw.println("<head>");
        pw.println("<meta charset=\"UTF-8\">");
        pw.println("<title>用户列表</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<center>");
        pw.println("<h1>用户列表</h1>");
        pw.println("<table border=\"2\">");
        pw.println("<tr>");
        pw.println("<td>");
        pw.println("用户名");
        pw.println("</td>");
        pw.println("<td>");
        pw.println("密码");
        pw.println("</td>");
        pw.println("<td>");
        pw.println("昵称");
        pw.println("</td>");
        pw.println("<td>");
        pw.println("年龄");
        pw.println("</td>");
        pw.println("<td>");
        pw.println("操作");
        pw.println("</td>");
        pw.println("</tr>");
        for (User user:userList){
            pw.println("<tr>");
            pw.println("<td>"+user.getUsername()+"</td>");
            pw.println("<td>"+user.getPassword()+"</td>");
            pw.println("<td>"+user.getNickname()+"</td>");
            pw.println("<td>"+user.getAge()+"</td>");
            pw.println("<td>");
            pw.println("<a href=\"/myweb/deleteUser?username="+user.getUsername()+"\"target=\"_self\">删除</a>");
            pw.println("</td>");
            pw.println("</tr>");
        }
        pw.println("</table>");
        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");
        pw.flush();
        pw.close();
    }
    @RequestMapping("/myweb/deleteUser")
    public void deleteUser(HttpServletRequest request,HttpServletResponse response){
        String username=request.getParameter("username");
        File userFile=new File(userDir,username+".obj");
        userFile.delete();
        File html=new File(staticDir,"/myweb/deleteUserSuccess.html");
        response.setContentFile(html);

    }
}
